package test.transferFile.server;

import java.io.IOException;
import java.io.RandomAccessFile;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import test.transferFile.common.MyFile;

public class MinaFileServerHandler extends IoHandlerAdapter {

  private RandomAccessFile randomAccessFile=null;

  @Override
  public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
    super.exceptionCaught(session, cause);
  }

  @Override
  public void messageReceived(IoSession session, Object message) throws Exception {
    MyFile myFile=(MyFile)message;
    // System.out.println(myFile);
    int length=myFile.getLength();
    int pos=myFile.getPos();
    byte[] bufferByte=new byte[length];
    myFile.getData().get(bufferByte);
    //
    write("e:\\test\\" + myFile.getName(), pos, bufferByte);
  }

  public void write(String filePath, int pos, byte[] data) throws IOException {
    if(randomAccessFile == null) {
      randomAccessFile=new RandomAccessFile(filePath, "rw");
    }
    randomAccessFile.seek(pos);
    randomAccessFile.write(data);
  }

  @Override
  public void messageSent(IoSession session, Object message) throws Exception {
    super.messageSent(session, message);
  }

  @Override
  public void sessionClosed(IoSession session) throws Exception {
    if(randomAccessFile != null) {
      System.out.println("close write io because sessionClosed");
      randomAccessFile.close();
      randomAccessFile=null;
    }
  }

  @Override
  public void sessionCreated(IoSession session) throws Exception {
    super.sessionCreated(session);
  }

  @Override
  public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
    if(randomAccessFile != null) {
      System.out.println("close write io because sessionIdle");
      randomAccessFile.close();
      randomAccessFile=null;
    }
  }

  @Override
  public void sessionOpened(IoSession session) throws Exception {
    super.sessionOpened(session);
  }
}
